package org.frxm.utilslibrary;

import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

/**
 * 作者 frxm
 * 时间 2017/1/4
 * 版本 1
 * DES加密
 * 对称加密
 * 具有加密和解密，要求密钥必须一致，低级加密相对不安全，速度快
 */

public class DES {
    //初始化密钥
    public static Key initKey()
    {
        //密钥的随机数对象
        SecureRandom random=new SecureRandom();
        try {
            KeyGenerator key=KeyGenerator.getInstance("DES");
            key.init(64,random);
            SecretKey sk=key.generateKey();
            return sk;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /*加密，参数说明：密钥Base64格式，要加密的数据*/
    public static byte[] encryptDES(Key key,byte[] data){
        try {
            Cipher cipher=Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE,key);
            return cipher.doFinal(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /*解密*/
    public static byte[] decodeDES(Key key,byte[]data)
    {
        try {
            Cipher cipher=Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE,key);
            return cipher.doFinal(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
